package com.binguo.wxapi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.UrlUtils;
import com.binguo.model.model.Customer;
import com.binguo.model.wxapi.vo.WxGongZHTokenVO;
import com.binguo.common.paymodel.WXGongZHConfig;
import com.binguo.wxapi.form.WXGongZHSubMessageForm;
import com.binguo.wxapi.form.WXGongZHMessageFrom;
import com.binguo.wxapi.vo.WXGongZongHMessageDataContentVO;
import com.binguo.wxapi.vo.WXGongZongHMessageDataVO;
import com.binguo.wxapi.vo.WXGongZongHMessageVO;
import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.Map;
import java.util.UUID;

import static com.binguo.common.exception.ErrorCode.CUSTOMER_NOT_EXIST;

/**
 * @author yuritian
 * @Title: WXGongZHService
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-12-1713:01
 */
@Service
public class WXGongZHService{

    @Autowired
    WxFaceService wxFaceService;

    @Autowired
    WXCustomerService wxCustomerService;

    @Resource
    RedisLockService redisLockService;

    private final Logger logger = LoggerFactory.getLogger(WXGongZHService.class);

    private String ipAddress;

    public String wxapiFilepath = "/usr/local/nginx/html";


    public WXGongZHService(){
//        this.ipAddress = "binguoai.com";
        this.ipAddress = System.getenv().get("ipAddress");
    }


    public void getWxToken(){
        RestTemplate restTemplate = new RestTemplate();
        String result=restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ WXGongZHConfig.appId +"&secret=" + WXGongZHConfig.secret,String.class);
        logger.info(result);
        JSONObject tokenResult = JSONObject.parseObject(result);
        String token = tokenResult.getString("access_token");
        logger.info("本次获取token是:  " + token);
        //WXGongZHConfig.setAccessToken(token);
        redisLockService.setKey("wxGongZHToken",token,60000000000L);
        result = restTemplate.getForObject("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token + "&type=jsapi",String.class);
        logger.info(result);
        JSONObject ticketResult = JSONObject.parseObject(result);
        String ticket = ticketResult.getString("ticket");
        //WXGongZHConfig.setJsapiTicket(ticket);
        redisLockService.setKey("ticket",ticket,60000000000L);
        logger.info("本次获取ticket是:  " + ticket);
    }

    public WxGongZHTokenVO getGongZHTokenVO(String url){
        String ticket = redisLockService.get("ticket");
        if (ticket == null || ticket.equals("")){
            getWxToken();
            ticket = redisLockService.get("ticket");
        }
        ticket = ticket.replaceAll("\"", "");
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        WxGongZHTokenVO wxGongZHTokenVO = new WxGongZHTokenVO();
        wxGongZHTokenVO.setAppid(WXGongZHConfig.appId);
        wxGongZHTokenVO.setNoncestr(nonce_str);
        wxGongZHTokenVO.setTimestamp(timestamp);
        wxGongZHTokenVO.setTicket(ticket);
        wxGongZHTokenVO.setUrl(url);
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        String signStr = "jsapi_ticket=" + ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;

        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(signStr.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
            logger.info("本次签名为:  "+signature);
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        wxGongZHTokenVO.setSignature(signature);

        return wxGongZHTokenVO;
    }


    public void uploadFace(String mediaId,Integer customerId){
        String uuid = UUID.randomUUID().toString();
        StringBuffer outputFilepathStringBuffer = new StringBuffer("/usr/local/nginx/html/images/faces/");

        /*StringBuffer outputFilepathStringBuffer = new StringBuffer("C:/Program Files (x86)/apache-tomcat-8.5.47/webapps/ROOT/");*/

        File dirOutput = new File(outputFilepathStringBuffer.toString());
        if (!dirOutput.exists()) {
            dirOutput.mkdir();
        }
        String newFileName = outputFilepathStringBuffer.append(uuid).append(".png").toString();
        logger.info(newFileName);

        String httpFileName = new StringBuffer("http://")
                        .append(ipAddress)
                        .append("/images/faces/")
                        .append(uuid).append(".png").toString();
        /*String httpFileName = new StringBuffer("http://")
                .append("123.206.224.209")
                .append(":8080/")
                .append(uuid).append(".png").toString();*/
        logger.info(httpFileName);

        String wxGZHToken = redisLockService.get("wxGongZHToken");

        wxGZHToken = wxGZHToken.replaceAll("\"", "");

        String imgUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token="+wxGZHToken+"&media_id="+mediaId;


        boolean result = downloadWxGongZHNetImage(imgUrl,newFileName);
        if (!result){
            throw new ServiceException("图片下载失败");
        }

        File img = new File(newFileName);

        long imgSize = img.length()/1024;

        if (imgSize > 5120){
            long s1 = System.currentTimeMillis();
            try {
                commpressPicCycle(newFileName,5120,0.8);
            } catch (IOException e) {
                e.printStackTrace();
                throw new ServiceException("图片压缩失败");
            }
            long s2 = System.currentTimeMillis();
            logger.info("压缩时长为:" + (s2 - s1));
        }
        Customer customer = wxCustomerService.getById(customerId);
        if (customer == null) {
            throw new ServiceException(CUSTOMER_NOT_EXIST);
        }
        wxFaceService.addFaceNew(customer, httpFileName);
    }

    public boolean downloadWxGongZHNetImage(String srcImgPath, String filepath) {
        BufferedImage srcImage = null;
        System.out.println(srcImgPath);
        try {
            srcImage = ImageIO.read(new URL(srcImgPath));

            File f1 = new File(filepath);
            ImageIO.write(srcImage, "png", f1);
            return true;
        } catch (IOException e) {
            logger.info("读取图片文件出错！" + e.getMessage());
            e.printStackTrace();
        }
        return false;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    public static void commpressPicCycle(String desPath , long desFileSize,
                                         double accuracy) throws IOException{
        File imgFile = new File(desPath);
        long fileSize  = imgFile.length();
        if(fileSize <= desFileSize * 512){
            return;
        }
        //计算宽高
        BufferedImage  bim = ImageIO.read(imgFile);
        int imgWidth = bim.getWidth();
        int imgHeight = bim.getHeight();
        int desWidth = new BigDecimal(imgWidth).multiply(
                new BigDecimal(accuracy)).intValue();
        int desHeight = new BigDecimal(imgHeight).multiply(
                new BigDecimal(accuracy)).intValue();
        Thumbnails.of(desPath).size(desWidth, desHeight).outputQuality(accuracy).toFile(desPath);
        //如果不满足要求,递归直至满足要求
        commpressPicCycle(desPath, desFileSize, accuracy);
    }

    public static void main(String[] args) {
        String newFileName = "/Users/jay/IdeaProjects/binguo/wxapi/target/WechatIMG795.jpeg";
        long s1 = System.currentTimeMillis();
        try {
            commpressPicCycle(newFileName,5120,0.8);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long s2 = System.currentTimeMillis();
        System.err.println("压缩时长为:" + (s2 - s1));
    }

    /**
     * 微信公众号一次性订阅消息，2020 03.28未线上测试
     * @param wxGongZHSubMessageForm
     * @return
     * @throws IOException
     */
    public Map sendSubMessage(WXGongZHSubMessageForm wxGongZHSubMessageForm)throws IOException{
        String token = redisLockService.get("wxGongZHToken");
        if (token == null || token.equals("")){
            getWxToken();
            token = redisLockService.get("wxGongZHToken");
        }
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/subscribe?access_token="+token;
        WXGongZongHMessageVO wxGongZongHMessageVO = new WXGongZongHMessageVO();
        WXGongZongHMessageDataVO wxGongZongHMessageDataVO = new WXGongZongHMessageDataVO();
        wxGongZongHMessageDataVO.setContent(new WXGongZongHMessageDataContentVO("测试消息","#FFFFFF"));
        wxGongZongHMessageVO.setTouser(wxGongZHSubMessageForm.getOpenId());
        wxGongZongHMessageVO.setScene("scene");
        wxGongZongHMessageVO.setTemplate_id(wxGongZHSubMessageForm.getTemplate_id());
        wxGongZongHMessageVO.setTitle("测试");
        wxGongZongHMessageVO.setData(wxGongZongHMessageDataVO);
        String json = JSON.toJSONString(wxGongZongHMessageVO);
        JSONObject jsonObject = JSON.parseObject(json);
        return UrlUtils.send2(url,jsonObject,"utf-8");
    }


    /**
     * 微信模版消息   2020 03.28(模版主体申请还未成功，模版还未申请)
     * @param wxGongZHMessageForm
     * @return
     * @throws IOException
     */
    public Map sendMessage(WXGongZHMessageFrom wxGongZHMessageForm)throws IOException{
        String token = redisLockService.get("wxGongZHToken");
        if (token == null || token.equals("")){
            getWxToken();
            token = redisLockService.get("wxGongZHToken");
        }
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        String json = JSON.toJSONString(wxGongZHMessageForm);
        JSONObject jsonObject = JSON.parseObject(json);
        return UrlUtils.send2(url,jsonObject,"utf-8");
    }




}
